package com.gtw.modules.api.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.gtw.common.annotation.AuthIgnoreApi;
import com.gtw.common.annotation.LoginUserApi;
import com.gtw.common.utils.PayStatus;
import com.gtw.common.utils.Query;
import com.gtw.common.utils.R;
import com.gtw.dto.TbOrderDto;
import com.gtw.dto.TdAddressDto;
import com.gtw.modules.api.service.*;
import com.gtw.modules.base.service.TbCityService;
import com.gtw.modules.base.service.TbDistrictService;
import com.gtw.modules.base.service.TbProvinecService;
import com.gtw.modules.dao.TbDiscountDao;
import com.gtw.modules.entity.*;
import com.gtw.modules.sys.service.SysTbActivityCommodityService;
import com.gtw.utils.EntityDtoConverter;
import com.gtw.utils.JSONUtils;
import com.gtw.utils.OrderUtil;
import com.gtw.utils.UidUtil;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * 订单
 *
 * @author wuye
 * @email www.baidu.com
 * @date 2018-02-06 15:19:47
 */
@RestController
@RequestMapping("/api/order")
public class TbOrderController {

    @Autowired
    private TbOrderService tbOrderService;

    @Autowired
    private TbShoppingCartServices tbShoppingCartServices;

    @Autowired
    private TbAddressService tbAddressService;

    @Autowired
    private TbCityService tbCityService;

    @Autowired
    private TbDistrictService tbDistrictService;

    @Autowired
    private TbProvinecService tbProvinecService;

    @Autowired
    private SysTbActivityCommodityService tbActivityCommodityService;

    @Autowired
    private TbCommodityService tbCommodityService;

    @Autowired
    private TbCommodityPropertyService tbCommodityPropertyService;

    @Autowired
    private TbPropertyService tbPropertyService;

    @Autowired
    private TbDiscountDao tbDiscountDao;

    @Autowired
    private TbUserService tbUserService;

    /**
     * 查询列表
     *
     * @param params
     * @returnapi
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params, @LoginUserApi TbUser tbUser) {
        params.put("uid", tbUser.getUuid());
        //查询列表数据
        Query query = new Query(params);
        Page<TbOrder> pageUtil = new Page<TbOrder>(query.getPage(), query.getLimit());
        Page<TbOrder> page = tbOrderService.queryPageList(pageUtil, query);
        List<TbOrderDto> tbOrderDtoList = new ArrayList<>();
        EntityDtoConverter edc = new EntityDtoConverter();
        for (int i = 0; i < page.getRecords().size(); i++) {
            TbOrderDto tbOrderDto = new TbOrderDto();
            try {
                tbOrderDto = (TbOrderDto) edc.entityConvertDto(page.getRecords().get(i), tbOrderDto);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            JSONArray ja = JSONArray.fromObject(page.getRecords().get(i).getShoppingcartid());
            List<TbShoppingCart> tbShoppingCartList = new ArrayList<>();
            for (int j = 0; j < ja.size(); j++) {
                TbShoppingCart tbShoppingCart = tbShoppingCartServices.selectByPrimaryKey(Integer.parseInt(ja.get(j).toString()));
                tbShoppingCartList.add(tbShoppingCart);
            }
            tbOrderDto.setTbShoppingCartList(tbShoppingCartList);
            tbOrderDtoList.add(tbOrderDto);
        }
        Page<TbOrderDto> tbOrderDtoPage = new Page<TbOrderDto>();
        tbOrderDtoPage.setRecords(tbOrderDtoList);
        return R.ok().put("data", tbOrderDtoPage);
    }

    /**
     * 下单
     *
     * @returnapi
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public R save(String ids, @LoginUserApi TbUser tbUser, Integer addressid, String channel, String remark, Integer aid) {

        //创建订单
        TbOrder tbOrder = new TbOrder();
        tbOrder.setIsdelete(false);
        tbOrder.setCreatedate(new Date());
        tbOrder.setAddressid(addressid);
        tbOrder.setBillno(OrderUtil.getOrderNo());
        tbOrder.setGuid(UidUtil.getUUID());
        tbOrder.setUid(tbUser.getUuid());
        tbOrder.setIspay(false);
        tbOrder.setOrderstatus(PayStatus.unpaid.getName());
        tbOrder.setUsername(tbUser.getUsername());
        tbOrder.setShoppingcartid(ids);
        tbOrder.setChannel(channel);
        tbOrder.setRemark(remark);
        tbOrder.setAid(aid);
        List<TbOrder> list = tbOrderService.queryByUid(tbOrder.getUid());
        if (list.size() <= 0) {
            tbOrder.setIsfirst(0);
        } else {
            tbOrder.setIsfirst(1);
        }

        //判断是否为代理
        TbUser tbUser1 = tbUserService.queryById(tbUser.getParentid());
        if (tbUser1 != null) {
            if (tbUser1.getType() == 2) {
                tbOrder.setProxyuserid(tbUser1.getUserId());
                tbOrder.setIsproxy(1);
            } else {
                tbOrder.setIsproxy(0);
            }
        }

        float money = 0;
        float discountMoney = 0;
        float freight = 999999999f;
        JSONArray ja = JSONArray.fromObject(ids);
        for (int i = 0; i < ja.size(); i++) {
            TbShoppingCart tbShoppingCart = tbShoppingCartServices.selectByPrimaryKey(Integer.parseInt(ja.get(i).toString()));
            if (aid == 0) {
                money += tbShoppingCart.getPrice() * tbShoppingCart.getCommoditynumber();
            } else {
                TbActivityCommodity tbActivityCommodity = tbActivityCommodityService.queryObject(aid);
                int shengyu = tbActivityCommodity.getTotalStore() - tbActivityCommodity.getReserve();
                if (shengyu<tbShoppingCart.getCommoditynumber()){
                    return R.error("下单库存大于活动库存,不能下单");
                }
                money += tbActivityCommodity.getNowprice() * tbShoppingCart.getCommoditynumber();
                //增加销量
                tbActivityCommodityService.addStore(aid,tbShoppingCart.getCommoditynumber());
            }
            if (freight > tbShoppingCart.getFreight()) {
                freight = tbShoppingCart.getFreight();
            }
            tbShoppingCart.setStatus(true);
            tbShoppingCartServices.updateByPrimaryKey(tbShoppingCart);
        }
        if (aid == 0) {
            //判断优惠
            List<TbOrder> tbOrderList = tbOrderService.queryByUid(tbUser.getUuid());
            if (tbUser.getType() == 1) {
                TbDiscount tbDiscount = tbDiscountDao.selectByType(0);
                if (tbOrderList.size() <= 0) {
                    if (tbDiscount.getFirstDiscount() != 0) {
                        discountMoney = money - (money * (float) (tbDiscount.getFirstDiscount() / 100));
                    } else {
                        discountMoney = money;
                    }
                } else {
                    if (tbDiscount.getDiscount() != 0) {
                        discountMoney = money - (money * (float) (tbDiscount.getDiscount() / 100));
                    } else {
                        discountMoney = money;
                    }
                }
            } else if (tbUser.getType() == 2) {
                TbDiscount tbDiscount = tbDiscountDao.selectByType(1);
                if (tbOrderList.size() <= 0) {
                    if (tbDiscount.getFirstDiscount() != 0) {
                        discountMoney = money - (money * (float) (tbDiscount.getFirstDiscount() / 100));
                    } else {
                        discountMoney = money;
                    }
                } else {
                    if (tbDiscount.getDiscount() != 0) {
                        discountMoney = money - (money * (float) (tbDiscount.getDiscount() / 100));
                    } else {
                        discountMoney = money;
                    }
                }
            } else {
                discountMoney = money;
            }
        } else {
            discountMoney = money;
        }
        if (money < 6800) {
            discountMoney += freight;
            tbOrder.setFreight(freight);
        } else {
            tbOrder.setFreight(0f);
        }

        tbOrder.setTotalfee(discountMoney);

        tbOrderService.save(tbOrder);
        return R.ok().put("data", tbOrder);
    }

    /**
     * 计算优惠价格
     *
     * @returnapi
     */
    @RequestMapping(value = "/dis", method = RequestMethod.POST)
    public R dis(String ids, @LoginUserApi TbUser tbUser, int aid) {
        Map<String, Object> map = new HashMap<>();
        float money = 0;
        float discountMoney = 0;
        float freight = 999999999f;
        JSONArray ja = JSONArray.fromObject(ids);
        for (int i = 0; i < ja.size(); i++) {
            TbShoppingCart tbShoppingCart = tbShoppingCartServices.selectByPrimaryKey(Integer.parseInt(ja.get(i).toString()));
            if (aid == 0) {
                money += tbShoppingCart.getPrice() * tbShoppingCart.getCommoditynumber();
            } else {
                TbActivityCommodity tbActivityCommodity = tbActivityCommodityService.queryObject(aid);
                money += tbActivityCommodity.getNowprice() * tbShoppingCart.getCommoditynumber();
            }
            if (freight > tbShoppingCart.getFreight()) {
                freight = tbShoppingCart.getFreight();
            }

            tbShoppingCart.setStatus(true);
            tbShoppingCartServices.updateByPrimaryKey(tbShoppingCart);
        }
        if (aid == 0) {
            //判断优惠
            List<TbOrder> tbOrderList = tbOrderService.queryByUid(tbUser.getUuid());
            if (tbUser.getType() == 1) {
                TbDiscount tbDiscount = tbDiscountDao.selectByType(0);
                if (tbOrderList.size() <= 0) {
                    if (tbDiscount.getFirstDiscount() != 0) {
                        discountMoney = money - (money * (float) (tbDiscount.getFirstDiscount() / 100));
                    } else {
                        discountMoney = money;
                    }
                } else {
                    if (tbDiscount.getDiscount() != 0) {
                        discountMoney = money - (money * (float) (tbDiscount.getDiscount() / 100));
                    } else {
                        discountMoney = money;
                    }
                }
            } else if (tbUser.getType() == 2) {
                TbDiscount tbDiscount = tbDiscountDao.selectByType(1);
                if (tbOrderList.size() <= 0) {
                    if (tbDiscount.getFirstDiscount() != 0) {
                        discountMoney = money - (money * (float) (tbDiscount.getFirstDiscount() / 100));
                    } else {
                        discountMoney = money;
                    }
                } else {
                    if (tbDiscount.getDiscount() != 0) {
                        discountMoney = money - (money * (float) (tbDiscount.getDiscount() / 100));
                    } else {
                        discountMoney = money;
                    }
                }
            } else {
                discountMoney = money;
            }
        } else {
            discountMoney = money;
        }
        map.put("discount", money - discountMoney);
        map.put("money", money);
        if (money < 6800) {
            discountMoney += freight;
            map.put("discountMoney", discountMoney);
            map.put("freight", freight);
        } else {
            map.put("discountMoney", discountMoney);
            map.put("freight", 0);
        }
        return R.ok().put("data", map);
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public R delete(@RequestBody Integer[] ids) {
        int[] success = new int[ids.length];
        for (int i = 0; i < ids.length; i++) {
            TbOrder tbOrder = tbOrderService.queryObject(ids[i]);
            if (!tbOrder.getIspay()) {
                tbOrder.setIsdelete(true);
                tbOrderService.update(tbOrder);
            }
            success[i] = ids[i];
        }
        return R.ok().put("data", success);
    }


    /**
     * 信息
     */
    @RequestMapping("/info")
    public R info(@LoginUserApi TbUser tbUser, String billno, String orderstatus) {
        TbOrderDto tbOrderDto = new TbOrderDto();
        TbOrder tbOrder = tbOrderService.queryInfo(tbUser.getUuid(), billno, orderstatus);
        EntityDtoConverter edc = new EntityDtoConverter();
        try {
            //查询地址详细信息
            tbOrderDto = (TbOrderDto) edc.entityConvertDto(tbOrder, tbOrderDto);
            TbAddress address = tbAddressService.queryObject(tbOrder.getAddressid());
            TdAddressDto tdAddressDto = new TdAddressDto();
            tdAddressDto = (TdAddressDto) edc.entityConvertDto(address, tdAddressDto);
            tdAddressDto.setCityname(tbCityService.findByCityId(address.getCityid()).getCityname());
            tdAddressDto.setDistrictname(tbDistrictService.findByDistrictId(address.getDistrictid()).getDistrictname());
            tdAddressDto.setProvincename(tbProvinecService.queryObject(address.getProvinceid()).getProvincename());
            tbOrderDto.setTbAddressDto(tdAddressDto);

            //查询商品详细信息
            JSONArray ja = JSONUtils.toJSONArray(tbOrder.getShoppingcartid());
            List<TbShoppingCart> tbShoppingCartList = new ArrayList<>();
            for (int i = 0; i < ja.size(); i++) {
                tbShoppingCartList.add(tbShoppingCartServices.selectByPrimaryKey(ja.getInt(i)));
            }
            tbOrderDto.setTbShoppingCartList(tbShoppingCartList);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return R.ok().put("data", tbOrderDto);
    }


    /**
     * 确认收货
     */
    @RequestMapping("/enter")
    public R enter(@LoginUserApi TbUser tbUser, String billno) {
        TbOrderDto tbOrderDto = new TbOrderDto();
        TbOrder tbOrder = tbOrderService.queryBybillno(billno);
        if (tbOrderService.queryInfo(tbUser.getUuid(), billno, tbOrder.getOrderstatus()) != null) {
            tbOrder.setOrderstatus(PayStatus.uncommented.getName());
            tbOrder.setUpdatedate(new Date());
            tbOrder.setUsername(tbUser.getUsername());
            tbOrderService.update(tbOrder);
        } else {
            return R.error("未查询到订单信息！");
        }
        return R.ok().put("data", tbOrderDto);
    }

    /**
     * 退款申请
     * 已测试
     */
    @AuthIgnoreApi
    @RequestMapping("/refund")
    public R doRefund(String orderno, int type, String refunddetails, String refundpic, int refundstatus) throws Exception {
        TbOrder tbOrder = tbOrderService.queryBybillno(orderno);
        if (tbOrder.getOrderstatus().equals(PayStatus.beforedeliver.getName()) || tbOrder.getOrderstatus().equals(PayStatus.delivering.getName())) {
            if (type == 0) {
                tbOrder.setOrderstatus(PayStatus.refund.getName());
            } else {
                tbOrder.setOrderstatus(PayStatus.refundgoods.getName());
            }
            tbOrder.setRefundstatus(refundstatus);
            tbOrder.setRefunddetails(refunddetails);
            tbOrder.setRefundpic(refundpic);
            tbOrder.setRefundtype(type);
            tbOrderService.update(tbOrder);
            return R.ok();
        } else {
            return R.error("订单状态不正确!");
        }
    }


    /**
     * 信息
     */
    @RequestMapping("/bargin")
    public R bargin(@LoginUserApi TbUser tbUser, String commodityid, String aid) {

        TbOrder tbOrder = tbOrderService.queryInfoByBargain(tbUser.getUuid(), commodityid, aid);
        if (tbOrder == null) {
            return R.error("未查询到订单信息！");
        }
        return R.ok().put("data", tbOrder);
    }
}
